#import "dfhgwhruebvhrheymournrural.h"
#import "dfhgwhruebvhrheyoutwarddelegate.h"
#import "dfhgwhruebvhrheyluggagerecorder.h"
#import "dfhgwhruebvhrheybulletinalterViewController.h"
#import "dfhgwhruebvhrheyerroneousmaintainViewController.h"
@interface dfhgwhruebvhrheybulletinalterViewController ()
@property (nonatomic, strong) dfhgwhruebvhrheymournrural *timer;
@property (nonatomic, assign) BOOL canChangePhone;
@end
@implementation dfhgwhruebvhrheybulletinalterViewController {
    UIView *bgView;
    UILabel *phoneLabel;
    UITextField *phone;
    UIView *phoneView;
    UILabel *codeLabel;
    UITextField *code;
    UIButton *sender;
    UIView *codeView;
    UIButton *confirmBtn;
    int cutdown;
}
- (dfhgwhruebvhrheymournrural *)timer {
    if (_timer == nil) {
        _timer = [[dfhgwhruebvhrheymournrural alloc] init];
    }
    return _timer;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadUI];
}
- (void)loadUI {
    self.canChangePhone = NO;
    cutdown = dhgfywegwygeydwleakconceal;
    [self configBackIcon:@"dhgfywegwygeydwcurvereciprocal"];
    self.navigationStyle = dhgfywegwygeydwreciprocaltransport;
    self.navigationItem.title = @"Change phone number";
    bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    phoneLabel = [[UILabel alloc] init];
    phoneLabel.font = [UIFont regular:15];
    phoneLabel.textColor = @"#3B414B".dhgfywegwygeydwlearneddesignate;
    phoneLabel.text = self.isCurrentMobile ? @"Old phone number" : @"New phone number";
    [bgView addSubview:phoneLabel];
    codeLabel = [[UILabel alloc] init];
    codeLabel.font = [UIFont regular:15];
    codeLabel.textColor = @"#3B414B".dhgfywegwygeydwlearneddesignate;
    codeLabel.text = @"Verify code";
    [bgView addSubview:codeLabel];
    phoneView = [[UIView alloc] init];
    phoneView.layer.cornerRadius = 10;
    phoneView.backgroundColor = @"#F6F6F6".dhgfywegwygeydwlearneddesignate;
    [bgView addSubview:phoneView];
    UIView *leftIV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 45)];
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 45)];
    leftLabel.text = @"+63";
    leftLabel.font = [UIFont regular:15];
    leftLabel.textColor = @"#3B414B".dhgfywegwygeydwlearneddesignate;
    [leftIV addSubview:leftLabel];
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:@"Please fill in"];
    [attribute addAttributes:@{NSForegroundColorAttributeName:@"#CCCCCC".dhgfywegwygeydwlearneddesignate, NSFontAttributeName: [UIFont regular:15]} range:NSMakeRange(0, attribute.length)];
    phone = [[UITextField alloc] init];
    phone.attributedPlaceholder = attribute;
    phone.font = [UIFont regular:15];
    phone.textColor = @"#3B414B".dhgfywegwygeydwlearneddesignate;
    phone.leftViewMode = UITextFieldViewModeAlways;
    phone.leftView = leftIV;
    phone.keyboardType = UIKeyboardTypeNumberPad;
    [phoneView addSubview:phone];
    if(self.isCurrentMobile) {
        phone.userInteractionEnabled = NO;
        NSString *mobie = [[dfhgwhruebvhrheyoptionsaving getUserData].phone mutableCopy];
        if (mobie == nil) {
            return;
        }
        if (![mobie hasPrefix:@"0"]) {
            mobie = [NSString stringWithFormat:@"0%@",mobie];
        }
        mobie = [mobie stringByReplacingCharactersInRange:NSMakeRange(4, 4) withString:@"****"];
        phone.text = mobie;
    }
    codeView = [[UIView alloc] init];
    codeView.layer.cornerRadius = 10;
    codeView.layer.borderWidth = 0.5;
    codeView.layer.borderColor = @"#CCCCCC".dhgfywegwygeydwlearneddesignate.CGColor;
    [bgView addSubview:codeView];
    code = [[UITextField alloc] init];
    code.attributedPlaceholder = attribute;
    code.keyboardType = UIKeyboardTypeNumberPad;
    code.font = [UIFont regular:15];
    code.textColor = @"#3B414B".dhgfywegwygeydwlearneddesignate;
    [codeView addSubview:code];
    UIView *rightIV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 45)];
    sender = [UIButton buttonWithType:UIButtonTypeCustom];
    sender.layer.cornerRadius = 6;
    sender.tag = 100;
    sender.frame = CGRectMake(0, 7.5, 60, 30);
    sender.titleLabel.font = [UIFont regular:14];
    sender.backgroundColor = primary_color.dhgfywegwygeydwlearneddesignate;
    [sender setTitle:@"Send" forState:UIControlStateNormal];
    [rightIV addSubview:sender];
    [sender addTarget:self action:@selector(changePhoneViewBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    code.rightView = rightIV;
    code.rightViewMode = UITextFieldViewModeAlways;
    confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    confirmBtn.tag = 200;
    confirmBtn.layer.cornerRadius = 10;
    confirmBtn.titleLabel.font = [UIFont semiBold:18];
    confirmBtn.backgroundColor = primary_color.dhgfywegwygeydwlearneddesignate;
    [confirmBtn setTitle:@"Confirm" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bgView addSubview:confirmBtn];
    [confirmBtn addTarget:self action:@selector(changePhoneViewBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(codeInputTextChange:) name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)codeInputTextChange:(NSNotification *)not {
    UITextField *tf = (UITextField *)not.object;
    NSString *text = tf.text;
    if (code == tf) {
        if (text.length >= 4) {
            code.text = [text substringToIndex:4];
        }
    }
}
- (void)changePhoneViewBtnAction:(UIButton *)sender {
    [self.view endEditing:YES];
    if (sender.tag == 100) {
        if(self.isCurrentMobile) {
            [self sendSMS];
        }else {
            if (![phone.text dhgfywegwygeydwdesignatecommence]) {
                return [dfhgwhruebvhrheyoptionsaving.keyWindow show:@"Please enter the correct format for the phone number，which must start with 9, 09, 8 or 08"];
            }
            [self mobile_status];
        }
    }else {
        if(self.isCurrentMobile) {
            [self verifyCode];
        }else {
            if(self.canChangePhone) {
                [self updatePhone];
            }
        }
    }
}
- (void)startTimer {
    __weak typeof(self) weakSelf = self;
    [self.timer startWithAction:^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            [strongSelf updateTimer];
        });
    }];
}
- (void)sendSMS {
    NSString *api;
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{@"pgid":@"1"}];
    if(self.isCurrentMobile) {
        api = forgetPasswdCodeApi;
        params[@"mobile"] = [dfhgwhruebvhrheyoptionsaving getUserData].phone;
    }else {
        if (![phone.text dhgfywegwygeydwdesignatecommence]) {
            return [self.view show:@"Please enter valid phone number."];
        }
        api = registerCodeApi;
        params[@"mobile"] = phone.text;
    }
    __weak typeof(self) weakSelf = self;
    [[dfhgwhruebvhrheyluggagerecorder shareInstance] dhgfywegwygeydwbarrierawait:dhgfywegwygeydwawaitlamb path:api isEncrypt:YES withParams:params success:^(NSURLSessionDataTask * _Nonnull task, NSString * _Nonnull json) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dfhgwhruebvhrheysternideology *model = [dfhgwhruebvhrheysternideology yy_modelWithJSON:json];
        if (model.code == 200) {
            [strongSelf startTimer];
        }else {
            [dfhgwhruebvhrheyoptionsaving.keyWindow show:model.error];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"=== %@",error);
    }];
}
- (void)verifyCode {
    if (code.text.length == 0) {
        return [self.view show:@"Verification cannot be empty"];
    }
    if(code.text.length != 4) {
        return [self.view show:@"Please enter the correct verification code"];
    }
    NSDictionary *params = @{
        @"code": code.text,
        @"mobile": [dfhgwhruebvhrheyoptionsaving getUserData].phone
    };
    __weak typeof(self) weakSelf = self;
    [[dfhgwhruebvhrheyluggagerecorder shareInstance] dhgfywegwygeydwbarrierawait:dhgfywegwygeydwlambbreast path:checkMobileApi isEncrypt:YES withParams:params success:^(NSURLSessionDataTask * _Nonnull task, NSString * _Nonnull json) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dfhgwhruebvhrheysternideology *model = [dfhgwhruebvhrheysternideology yy_modelWithJSON:json];
        if (model.code == 200) {
            if (strongSelf.isCurrentMobile) {
                dfhgwhruebvhrheybulletinalterViewController *changeVC = [[dfhgwhruebvhrheybulletinalterViewController alloc] init];
                changeVC.isCurrentMobile = NO;
                [strongSelf.navigationController pushViewController:changeVC animated:YES];
            }
        }else {
            [dfhgwhruebvhrheyoptionsaving.keyWindow show:model.error];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"==== %@", error);
    }];
}
- (void)mobile_status {
    if (![phone.text dhgfywegwygeydwdesignatecommence]) {
        return [dfhgwhruebvhrheyoptionsaving.keyWindow show:@"Please enter valid phone number."];
    }
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = @{@"mobile": phone.text, @"pgid": @"1"};
    [[dfhgwhruebvhrheyluggagerecorder shareInstance] dhgfywegwygeydwbarrierawait:dhgfywegwygeydwlambbreast path:checkNewMobileExsitApi isEncrypt:NO withParams:params success:^(NSURLSessionDataTask * _Nonnull task, NSString * _Nonnull json) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dfhgwhruebvhrheysternideology *model = [dfhgwhruebvhrheysternideology yy_modelWithJSON:json];
        if (model.code == 201) {
            [strongSelf sendSMS];
            strongSelf.canChangePhone = YES;
        }else {
            [dfhgwhruebvhrheyoptionsaving.keyWindow show:model.error];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"=== %@", error);
    }];
}
- (void)updatePhone {
    if (code.text.length == 0) {
        return [self.view show:@"Verification cannot be empty"];
    }
    if(code.text.length != 4) {
        return [self.view show:@"Please enter the correct verification code"];
    }
    if (![phone.text dhgfywegwygeydwdesignatecommence]) {
        return [self.view show:@"Please enter valid phone number."];
    }
    NSDictionary *params = @{
        @"code": code.text,
        @"mobile": phone.text
    };
    __weak typeof(self) weakSelf = self;
    [[dfhgwhruebvhrheyluggagerecorder shareInstance] dhgfywegwygeydwbarrierawait:dhgfywegwygeydwawaitlamb path:updateNewMobileApi isEncrypt:YES withParams:params success:^(NSURLSessionDataTask * _Nonnull task, NSString * _Nonnull json) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dfhgwhruebvhrheysternideology *model = [dfhgwhruebvhrheysternideology yy_modelWithJSON:json];
        if (model.code == 200) {
            [strongSelf changeSuccess];
        }else {
            [dfhgwhruebvhrheyoptionsaving.keyWindow show:model.error];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"==== %@",error);
    }];
}
- (void)changeSuccess {
    [dfhgwhruebvhrheyoptionsaving logout];
    dfhgwhruebvhrheyerroneousmaintainViewController *successVC = [[dfhgwhruebvhrheyerroneousmaintainViewController alloc] init];
    [self.navigationController pushViewController:successVC animated:YES];
}
- (void)updateTimer {
    if (cutdown <= 0) {
        cutdown = dhgfywegwygeydwleakconceal;
        if (_timer) {
            [_timer cancel];
            _timer = nil;
        }
        sender.userInteractionEnabled = YES;
        sender.backgroundColor = primary_color.dhgfywegwygeydwlearneddesignate;
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sender setTitle:@"Send" forState:UIControlStateNormal];
    }else {
        sender.userInteractionEnabled = NO;
        sender.backgroundColor = @"#EEEEEE".dhgfywegwygeydwlearneddesignate;
        [sender setTitleColor:@"#AAAAAA".dhgfywegwygeydwlearneddesignate forState:UIControlStateNormal];
        [sender setTitle:[NSString stringWithFormat:@"%ds", cutdown] forState:UIControlStateNormal];
        cutdown -= 1;
    }
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.bottom.right.equalTo(self.view);
    }];
    [phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgView).offset(20);
        make.left.equalTo(bgView).offset(25);
        make.centerX.equalTo(bgView);
        make.height.mas_equalTo(21);
    }];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneLabel.mas_bottom).offset(10);
        make.left.centerX.equalTo(phoneLabel);
        make.height.mas_equalTo(45);
    }];
    [codeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneView.mas_bottom).offset(10);
        make.left.centerX.equalTo(phoneView);
        make.height.mas_equalTo(21);
    }];
    [codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(codeLabel.mas_bottom).offset(10);
        make.left.centerX.equalTo(phoneLabel);
        make.height.mas_equalTo(45);
    }];
    [phone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneView).offset(15);
        make.top.centerX.bottom.equalTo(phoneView);
    }];
    [code mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneView).offset(15);
        make.top.centerX.bottom.equalTo(codeView);
    }];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(codeView.mas_bottom).offset(50);
        make.left.centerX.equalTo(codeView);
        make.height.mas_equalTo(50);
    }];
}
- (void)backAction {
    if (_timer) {
        [_timer cancel];
        _timer = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
@end
